package com.xyy.saas.payment.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.cores.enums.PayModeEnum;
import com.xyy.saas.payment.dao.model.BankCardBind;
import com.xyy.saas.payment.dao.model.PayResultOrder;
import com.xyy.saas.payment.dao.model.PrePayOrder;
import com.xyy.saas.payment.manage.cores.api.PayOrderManageApi;
import com.xyy.saas.payment.manage.cores.dto.PayResultOrderDto;
import com.xyy.saas.payment.service.BankCardBindService;
import com.xyy.saas.payment.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service(version = "1.0.0")
@Slf4j
public class PayOrderManageApiImpl implements PayOrderManageApi {
    @Autowired
    private OrderService orderService;
    @Autowired
    private BankCardBindService bankCardBindService;

    @Override
    public List<PayResultOrderDto> queryByPayNos(List<String> payNos) {
        final List<PrePayOrder> prePayOrderByPayNos = orderService.getPrePayOrderByPayNos(payNos);

        final Map<String, PrePayOrder> prePayOrderMap = prePayOrderByPayNos.stream()
                .collect(Collectors.toMap(PrePayOrder::getPayNo, Function.identity(), (x1, x2) -> x1));

        final List<PayResultOrder> payResultOrders = orderService.selectPayResultOrderListByPayNos(payNos);
        List<PayResultOrderDto> result = new ArrayList<>(payResultOrders.size());
        for (PayResultOrder payResultOrder : payResultOrders) {
            PayResultOrderDto dto = new PayResultOrderDto();
            BeanUtils.copyProperties(payResultOrder,dto);
            if (PayModeEnum.JD_CARD.getMode().equals(payResultOrder.getPayChannel())) {
                final PrePayOrder prePayOrder = prePayOrderMap.get(payResultOrder.getPayNo());
                final String extra = prePayOrder.getExtra();
                if (StringUtils.isNotBlank(extra)) {
                    final JSONObject jsonObject = JSONObject.parseObject(extra);
                    final String contractNo = jsonObject.getString("contractNo");
                    BankCardBind bank = new BankCardBind();
                    bank.setContractNo(contractNo);
                    final BankCardBind bankCardBind = bankCardBindService.queryOneWithDesenCardNo(bank);
                    String cardType = "DE".equals(bankCardBind.getCardType())?"储蓄卡":"信用卡";
                    dto.setCardInfo(bankCardBind.getBankName()+cardType+"("+bankCardBind.getCardNo()+")");
                }
            }
            result.add(dto);
        }

        return result;
    }
}
